<template>
	<view class="evidence-management">
		<view class="container">
			<view class="header">
				<view class="top">
					<view class="title">{{ evidenceName }}</view>
				</view>
				<view class="upload-btn-box">
					<!-- 		<FileChoose ref="fileChooseRef" :showFileList="false" :config="fileChooseConfig" @on-upload="handleOnUpload">
						<view class="upload-btn-wrap">
							<button class="upload-btn" type="primary" size="mini">点击上传</button>
						</view>
					</FileChoose> -->
					<view class="upload-btn-wrap">

						<button class="upload-btn" type="primary" size="mini" @click="test">点击上传</button>
					</view>
				</view>

			</view>
			<view class="main">
				<view class="main-container">
					<view v-if="dataList.length" class="file-list">
						<view class="file-item" v-for="(item, index) in dataList" :key="index">
							<view class="item-wrap">
								<view class="head">
									<view class="file-preview" @click="handlePictureCardPreview(item)">
										<image v-if="getMainFileType(item) == 'video'" src="../../static/h5/video.png" mode="scaleToFill">
										</image>
										<image v-else-if="getMainFileType(item) == 'pdf'" src="../../static/h5/pdf.png" mode="scaleToFill" />
										<image v-else-if="getMainFileType(item) == 'image'" :src="item.url" mode="scaleToFill" />
										<template v-else-if="item.url && item.url.slice(0, 4) != 'blob'">
											<view style="height: 100%;" flex="main:center cross:center">无法识别的文件类型</view>
										</template>
										<view class="mask"></view>
									</view>
									<view class="close" @click="handleOnRemove(item, index)">x</view>
								</view>
								<view class="form">
									<component :is="componentId" v-model="item.form" @change="fileChange"></component>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="empty">
						<u-empty text="暂无数据" mode="list" icon-size="300" font-size="60"></u-empty>
					</view>
				</view>
			</view>
			<FooterBtn class="footer-btn" :pdfDownload="pdfDownload" :submitDis="false" @submit="submitForm" @cancel="handleCancel" />
		</view>
	</view>
</template>

<script>
	import {
		MODULE_DICTID,
		MODULE_DICTID_NAMES
	} from '@/const/modules/index.js'

	import ProfessionalDiagrams from './commonents/ProfessionalDiagrams.vue'
	import Sketches from './commonents/Sketches.vue'
	import EvidenceMaterials from './commonents/EvidenceMaterials.vue'
	import FireScenePhotos from './commonents/FireScenePhotos.vue'
	import VideoUploads from './commonents/VideoUploads.vue'

	import DataFlow from '@/pagesH5/mixins/DataFlow.js'
	import FooterBtn from '@/pagesH5/components/FooterBtn'

	import FileChoose from '@/uni_modules/file-choose/components/file-choose/file-choose.vue'

	import {
		uploadLocalFile
	} from '@/static/common/js/padLocalFileHandler.js'
	export default {
		mixins: [DataFlow],
		components: {
			ProfessionalDiagrams,
			Sketches,
			EvidenceMaterials,
			FireScenePhotos,
			VideoUploads,
			FileChoose,
			FooterBtn
		},
		data() {
			return {
				dataList: [],
				itemForm: {},
				fileChooseConfig: {
					size: 20,
					limit: 99,
					title: "",
					headers: this.headers,
					formData: {},
					automatic: false,
					fileMediatype: 'all',
					mediaTypeFileType: ''
					// mediaTypeFileType: 'dwg,png,jpeg,jpg,pdf'
				},
				device: ''
			}
		},
		computed: {
			getModuleKey() {
				const active = this.params.dictId
				const obj = {
					[MODULE_DICTID.specialty]: 'ProfessionalDiagrams',
					[MODULE_DICTID.sketch]: 'Sketches',
					[MODULE_DICTID.evidence]: 'EvidenceMaterials',
					[MODULE_DICTID.photo]: 'FireScenePhotos',
					[MODULE_DICTID.video]: 'VideoUploads'
				}
				return obj[active]
			},
			// 证据链名称
			evidenceName() {
				return MODULE_DICTID_NAMES[this.params.dictId]
			},
			// 初始化 子组件 下的表单
			getInitItemFormData() {
				return require(`./initForm/${this.getModuleKey}.js`).default(this)
			},
			// 动态组件id
			componentId() {
				return this.getModuleKey
			},
			// 获取文件 type
			getMainFileType() {
				return (file) => {
					if (file.type == 'application/pdf' || file.type == 'pdf') return 'pdf'
					if (file.type && file.type.indexOf('/') != '-1') return file.type.split('/')[0]

					const fileTypeMapping = {
						// image: 'image',
						jpg: 'image',
						jpeg: 'image',
						png: 'image',
						gif: 'image',
						mp4: 'video',
						mov: 'video',
						avi: 'video',
						wmv: 'video',
						pdf: 'pdf'
					}
					if (fileTypeMapping[file.type] != undefined) return fileTypeMapping[file.type]
					if ((file.url && file.url.indexOf('.') != '-1')) {
						const extension = file.url.split('.').pop().toLowerCase()

						const fileType = fileTypeMapping[extension] || '未知类型'
						return fileType
					}
					if (!file.type) return '未知类型'
					return file.type
				}
			},
		},
		onLoad() {
			const res = uni.getSystemInfoSync()
			let device = res.ua.split(';')[2]
			this.device = device
		},
		onReady() {
			uni.setNavigationBarTitle({
				title: MODULE_DICTID_NAMES[this.params.dictId]
			})
		},
		methods: {
			test() {
				plus.io.chooseFile({
					title: '选择文件',
					filetypes: ['pdf'], // 允许的文件类型  
					multiple: false, // 是否允许多选  
				}, (e) => {
					
					console.log(e);
					const tempFilePaths = e.files
					// 获取文件的虚拟路径
					const contentUri = decodeURIComponent(e.files[0])
					console.log(contentUri)
					let type = this.getMainFileType({
						url: contentUri
					})
					if(type == '未知类型'){ 
						uni.showModal({
							title:'提示',
							content:'未知类型，暂时不支持上传'
						})
						return
					}
					console.log(type);
					let fileName = contentUri.match(/\/([^/]+)$/)[1];
					let form = this.$u.deepClone(this.itemForm)
					let item = {
						fileName,
						url: contentUri,
						type,
						form,
					}
					this.dataList.push(item)
				})
			},
			// Context.getActivity
			afterHandleData(data) {
				let list = JSON.parse(JSON.stringify(data.fileList))
				let keys = Object.keys(this.itemForm)
				this.dataList = list.map(item => {
					let form = {}
					keys.forEach(itemKey => {
						form[itemKey] = item[itemKey]
					})
					return {
						...item,
						form
					}
				})
			},
			handleOnUpload(file) {
				let type = this.getMainFileType(file)
				console.log(file.url);
				let resultUrl = file.url.replace('/document/raw:', '')
				let form = this.$u.deepClone(this.itemForm)
				let item = {
					fileName: file.name,
					url: resultUrl,
					type,
					form,
				}
				this.dataList.push(item)
			},
			handleOnRemove(item, index) {
				this.dataList.splice(index, 1)
			},
			handlePictureCardPreview(file) {
				const fileChooseRef = this.$refs.fileChooseRef
				const {
					type,
					url
				} = file
				switch (type) {
					case 'image':
						fileChooseRef.previewImage(url)
						break;
					case 'video':
						fileChooseRef.previewVideo(url)
						break;
					case 'pdf' || 'application/pdf':
						fileChooseRef.previewPDF(url)
						break;
				}
			},
			fileChange(item) {
				console.log(item);
			},
			initForm() {
				this.itemForm = this.getInitItemFormData

				let initForm = {
					title: this.$u.timeFormat(new Date(), 'yyyymmddhhMM'),
					userName: this.params.nickName || '群众',
					fileList: [],
					remark: '',
				}
				return initForm
			},
			async submitFormBefore() {
				const {
					archivesId
				} = this.params
				// 循环map 去除form属性，并把form属性解构
				const dataList = this.dataList.map(item => {
					const {
						form,
						...rest
					} = item;
					return {
						...rest,
						...form
					}
				})
				// 将 每个item 下的 录音列表 文件循环 变为本应用下路径
				for (let i = 0; i < dataList.length; i++) {
					const item = dataList[i];
					console.log(item.studio);
					if (item.studio) {
						let studioUrlList = JSON.parse(item.studio)
						console.log(studioUrlList);
						for (let j = 0; j < studioUrlList.length; j++) {
							const studioItem = studioUrlList[j];
							if (studioItem) {
								console.log(studioItem);
								let fileName = studioItem.match(/\/([^/]+)$/)[1];
								console.log(fileName);
								studioUrlList[j] = await uploadLocalFile(archivesId, {
									url: studioItem,
									name: fileName,
									type: 'audio'
								});
							}
						}
					}
				}

				let fileListPromise = []
				// list下 上传的临时路径变更为 应用下路径
				dataList.forEach(item => {
					fileListPromise.push(uploadLocalFile(archivesId, {
						name: item.fileName,
						type: item.type,
						url: item.url,
					}))
				})

				let result = await Promise.all(fileListPromise)

				let fileList = dataList.map((item, index) => {
					return {
						...item,
						url: result[index]
					}
				})
				console.log(fileList);
				this.formData.fileList = fileList
			}
		}
	}
</script>
<style scoped lang="scss">
	.evidence-management {
		height: 100vh;
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		background-color: #fff;

		.container {
			margin: 0 88rpx;
			display: flex;
			flex-direction: column;
			height: 100%;
			overflow: hidden;

			.header {
				width: 100%;
				padding-bottom: 64rpx;

				.top {
					padding: 26rpx 48rpx;
					border-bottom: 2rpx solid rgba(0, 144, 225, .08);
					color: #4e5969;
					font-size: 16px;
					font-weight: bold;
				}

				.upload-btn-box {
					display: flex;
					justify-content: flex-end;
					padding: 48rpx 48rpx 0;
					color: #86909c;
					font-size: 16px;

					.upload-btn-wrap {
						display: flex;
						justify-content: flex-end;
						width: 100%;

						.upload-btn {
							margin: 0;
						}
					}

				}
			}

			.main {
				flex: 1;
				overflow: hidden;

				.main-container {
					height: 100%;
					overflow-y: auto;
					padding: 0 48rpx 0;

					.file-list {
						display: flex;
						flex-wrap: wrap;
						gap: 48rpx;
						margin-right: -48rpx;

						.file-item {
							flex: 0 0 calc(50% - 48rpx);
							background-color: #f8fdff;
							border-radius: 8rpx;
							border: 2rpx solid rgba(0, 144, 225, .16);

							.item-wrap {
								padding: 48rpx;

								.head {
									display: flex;
									justify-content: space-between;
									margin-bottom: 72rpx;

									.file-preview {
										position: relative;
										width: 160rpx;
										height: 160rpx;
										overflow: hidden;
										border-radius: 4px;

										image {
											width: 100%;
											height: 100%;
										}

										.mask {
											cursor: pointer;
											position: absolute;
											width: 100%;
											height: 100%;
											top: 0;
										}
									}

									.close {
										cursor: pointer;
									}
								}
							}
						}
					}
				}

				.empty {
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					padding-bottom: 64rpx;
				}
			}


			.footer-btn {
				padding: 20rpx 0;

				button {
					margin: 0;
				}
			}
		}
	}

	::v-deep .form {
		.form-wrap_item {
			.wrap {
				.form-item_input-wrap {
					.form-item_input {
						background-color: #EBF7FD;
						border: 1px solid rgba(0, 144, 225, 0.16);
						color: #0090E1;
						font-weight: bold;

						&:hover {
							border: 2rpx solid #0090E1;
						}
					}

					.phcolor {
						color: #98BEEA;
					}

					.form-item_icon {
						color: #1097e3;
					}
				}
			}
		}
	}



	::v-deep .u-form-item__body {
		.u-form-item--left__content {
			padding-right: 24rpx;
		}

		.u-form-item--right__content {
			height: 100%;

			.u-form-item--right__content__slot {
				height: 100%;

				.form-item_value {
					height: 100%;
					flex: 1;
					display: flex;
					align-items: center;
				}

				.form-item_icon {
					height: 100%;
					width: 50rpx;
					text-align: center;
					color: #c0c4cc;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}
</style>